import axios from "axios";
import { MessageBox, Message } from "element-ui";
// import store from "@/store";
import { getUser } from "@/utils/auth";
import router from "@/router/index"



// create an axios instance
const service = axios.create({
  baseURL: "http://152.136.13.69:8099/api", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    console.log(config,"请求拦截器打印");
    getUser()
    // do something before request is sent
    const user = window.localStorage.getItem("users");
    if (user) {
      let temp = JSON.parse(user);
      config.headers.token = temp.token;

      // console.log(config, "拦截器的打印");
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(

  (response) => {
    if (response.data.code == 401) {
      console.log("用户未登录");
      router.replace({
        path: '/login',
        // query: { redirect: router.currentRoute.fullPath }
      })
    }
    // console.log(response.headers);
    // if (response.headers.authentication) {
    //   // 响应头里面如果有这个字段，我们需要将这个字段存储到 localstorage，之后的请求都需要将这个 token 带到服务器
    //   // 这一步很重要，一定要将 token 存储到本地
    //   localStorage.adminToken = response.headers.authentication;
    // }
    return response.data;
  },
  (error) => {
    // console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
